package net.lab1024.sa.admin.module.yitihua;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.yitihua.domain.entity.Cfs119Community;
import net.lab1024.sa.admin.module.yitihua.domain.entity.Cfs119Compound;
import net.lab1024.sa.admin.module.yitihua.domain.entity.Cfs119House;
import net.lab1024.sa.admin.module.yitihua.service.Cfs119CarePersonService;
import net.lab1024.sa.admin.module.yitihua.service.Cfs119CommunityService;
import net.lab1024.sa.admin.module.yitihua.service.Cfs119CompoundService;
import net.lab1024.sa.admin.module.yitihua.service.Cfs119HouseService;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class SyncController {
    @Value("${integration.event.url:http://xfzhjg.bj.119.gov.cn/xfjgfw-xfjg}")
    private String URL;
    @Value("${integration.event.bjxfappId:22041288f3673e35b73a20e8b0c9b030}")
    private String bjxfappId;
    @Value("${integration.event.rsign:367y0k37r3094725}")
    private String rsign;
    // 缓存的token
    private String cachedToken;
    // token的获取时间
    private long tokenFetchTime;
    // token有效期，单位：毫秒
    private static final long TOKEN_EXPIRATION_TIME = 30 * 60 * 1000;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private Cfs119CommunityService cfs119CommunityService;
    @Resource
    private Cfs119CompoundService cfs119CompoundService;
    @Resource
    private Cfs119HouseService cfs119HouseService;
    @Resource
    private Cfs119CarePersonService cfs119CarePersonService;

    private String getToken(String bjxfrtime) {
        // 检查缓存的token是否有效
        if (cachedToken != null && System.currentTimeMillis() - tokenFetchTime < TOKEN_EXPIRATION_TIME) {
            log.info("一体化平台--使用缓存的token");
            return cachedToken;
        }
        JSONObject header = new JSONObject();
        header.put("bjxfappId", bjxfappId);
        header.put("bjxfrtime", bjxfrtime);
        header.put("bjxfrsign", SM4Utils.encryptData_ECB(String.valueOf(bjxfrtime), rsign));
        JSONObject result = null;
        try {
            result = HttpUtil.httpGet(URL + "/rest/client/token.do", header);
        } catch (Exception e) {
            log.error("一体化平台--获取token失败{}", e.getMessage());
            throw new RuntimeException(e);
        }
        String token = null;
        if (result.getInteger("responseCode") == 200) {
            JSONObject data = JSONObject.parseObject(result.getString("responseString"));
            if ("0".equals(data.getString("returnCode"))) {
                token = SM4Utils.decryptData_ECB(data.getString("token"), rsign);
                // 缓存新的token和获取时间
                cachedToken = token;
                tokenFetchTime = System.currentTimeMillis();
                //存入redis
                redisTemplate.opsForValue().set("yitihua:token", token, TOKEN_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
            }
        }
        return token;
    }

    @NoNeedLogin
    @RequestMapping("/yitihua/getCommunityListData")
    public String getCommunityListData(Cfs119Param params) throws InterruptedException {
        int pageSize = 100;
        int startPage = params.getStart() != null ? params.getStart() : 1; // 起始页
        int totalFetched = 0; // 累计获取的数据总量
        while (true) {
            params.setStart(startPage);
            params.setPageSize(pageSize);
            List<Cfs119Community> list = getDataByServiceCode(params, "XF-DICT-GET-COMMUNITY", Cfs119Community.class);
            int fetched = list.size();
            log.info("一体化平台--当前第{}页，获取社区数据{}条", startPage, fetched);
            if (fetched > 0) {
                // 累计总数
                totalFetched += fetched;
                // 批量插入
                cfs119CommunityService.addBatch(list);
            }
            // 判断是否还有下一页
            if (fetched < pageSize) {
                // 最后一页，跳出
                break;
            }
            // 继续下一页
            startPage++;
            // 限流，避免请求过快
            log.info("一体化平台--等待5秒后继续获取");
            Thread.sleep(5000); // 限流，避免请求过快
        }
        log.info("一体化平台--获取社区数据完成，共获取 {} 条", totalFetched);
        return String.valueOf(totalFetched); // 返回总条数
    }

    @NoNeedLogin
    @RequestMapping("/yitihua/getCompoundListData")
    public String getCompoundListData(Cfs119Param params) throws InterruptedException {
        int pageSize = 1000;
        int startPage = params.getStart() != null ? params.getStart() : 1; // 起始页
        int totalFetched = 0; // 累计获取的数据总量
        while (true) {
            params.setStart(startPage);
            params.setPageSize(pageSize);
            List<Cfs119Compound> list = getDataByServiceCode(params, "XF-DICT-GET-COMPOUND", Cfs119Compound.class);
            int fetched = list.size();
            log.info("一体化平台--当前第{}页，获取社区数据{}条", startPage, fetched);
            if (fetched > 0) {
                // 累计总数
                totalFetched += fetched;
                // 批量插入
                cfs119CompoundService.addBatch(list);
            }
            // 判断是否还有下一页
            if (fetched < pageSize) {
                // 最后一页，跳出
                break;
            }
            // 继续下一页
            startPage++;
            // 限流，避免请求过快
            log.info("一体化平台--等待5秒后继续获取");
            Thread.sleep(5000); // 限流，避免请求过快
        }
        log.info("一体化平台--获取社区数据完成，共获取 {} 条", totalFetched);
        return String.valueOf(totalFetched); // 返回总条数
    }


    @NoNeedLogin
    @RequestMapping("/yitihua/getHouseListData")
    public String getHouseListData(Cfs119Param params) {
        /*CompletableFuture.runAsync(() -> {

        });*/
        cfs119HouseService.sync(params);


        // 立即返回，不等待
        return "数据同步已启动，请稍后查看结果";
    }

    @NoNeedLogin
    @RequestMapping("/yitihua/getCarePersonListData")
    public String getCarePersonListData(Cfs119Param params) {
        cfs119CarePersonService.sync(params);
        // 立即返回，不等待
        return "数据同步已启动，请稍后查看结果";
    }

    public <T> List<T> getDataByServiceCode(Cfs119Param param, String serviceCode, Class<T> clazz) {
        String bjxfrtime = String.valueOf(System.currentTimeMillis());
        String token = getToken(bjxfrtime);

        HttpHeaders headers = new HttpHeaders();
        headers.add("bjxfappId", bjxfappId);
        headers.add("bjxfrtime", bjxfrtime);
        headers.add("bjxfrsign", SM4Utils.encryptData_ECB(bjxfrtime, token));
        headers.add("Accept", "application/json");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json");

        String url = URL + "/rest/open/microService.do?serviceCode=" + serviceCode;
        JSONObject response = RestTemplateUtil.post(headers, url, JSONObject.toJSONString(param));

        if (response != null && "0".equals(response.getString("returnCode"))) {
            JSONArray data = response.getJSONArray("data");
            List<T> list = data.toJavaList(clazz);
            log.info("【{}】调用成功，获取数据 {} 条", serviceCode, list.size());
            return list;
        } else {
            log.error("【{}】调用失败，响应内容: {}", serviceCode, response);
            return new ArrayList<>();
        }
    }

    @NoNeedLogin
    @RequestMapping("/yitihua/hello")
    public String hello() {
        return "hello";
    }

}
